function [DOMStruct] = parsexml(DOMNode)
%PARSEXML 将XML的DOM节点转换为MATLAB结构体
%
% Tips:
% 1. 可以与xmlread串联使用，如parsexml(xmlread(fileName))
%
% Input Arguments:
% DOMNode: Document Object Model节点，格式同xmlread的输出
%
% Output Arguments:
% DOMStruct: 代表DOM根节点的结构体，代表每个节点的结构体包含Name、Attibutes、Data、Children四个域，分别表示节点名、属性、数据与子节点

% Recurse over child nodes. This could run into problems with very deeply nested trees.
try
    DOMStruct = parseChildNodes(DOMNode);
catch exception
    error('Unable to parse DOM node.');
end

function children = parseChildNodes(theNode)
% Recurse over node children.
children = [];
if theNode.hasChildNodes
    childNodes = theNode.getChildNodes;
    numChildNodes = childNodes.getLength;
    allocCell = cell(1, numChildNodes);
    
    children = struct(             ...
        'Name', allocCell, 'Attributes', allocCell,    ...
        'Data', allocCell, 'Children', allocCell);
    
    for count = 1:numChildNodes
        theChild = childNodes.item(count-1);
        children(count) = makeStructFromNode(theChild);
    end
end

function nodeStruct = makeStructFromNode(theNode)
% Create structure of node info.
nodeStruct = struct(                        ...
    'Name', char(theNode.getNodeName),       ...
    'Attributes', parseAttributes(theNode),  ...
    'Data', '',                              ...
    'Children', parseChildNodes(theNode));

if any(strcmp(methods(theNode), 'getData'))
    nodeStruct.Data = char(theNode.getData);
else
    nodeStruct.Data = '';
end

function attributes = parseAttributes(theNode)
% Create attributes structure.
attributes = [];
if theNode.hasAttributes
    theAttributes = theNode.getAttributes;
    numAttributes = theAttributes.getLength;
    allocCell = cell(1, numAttributes);
    attributes = struct('Name', allocCell, 'Value', ...
        allocCell);
    
    for count = 1:numAttributes
        attrib = theAttributes.item(count-1);
        attributes(count).Name = char(attrib.getName);
        attributes(count).Value = char(attrib.getValue);
    end
end